package com.learn.hibernatevalidator.chapter02.containerelement.optional;

import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;

import java.lang.annotation.*;

/**
 * @author: liyf
 * @create: 2024-12-20 22:59
 **/
@Documented
@Constraint(validatedBy = {MinTowingCapacity.MinTowingCapacityValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MinTowingCapacity {

    // value 没有默认值时，在使用注解的时候必须传递参数过来
    long value();

    String message() default "必须大于 value 值";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class MinTowingCapacityValidator implements ConstraintValidator<MinTowingCapacity, Integer> {

        private Long min;

        @Override
        public void initialize(MinTowingCapacity constraintAnnotation) {
            min = constraintAnnotation.value();
        }

        @Override
        public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
            if (value == null) {
                return true;
            }

            return value >= min;
        }
    }
}
